<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Hook;
use app\common\model\Mineral as MineralModel;
/**
 * Token接口
 */
class Token extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        Hook::add('user_check', function ($user) {
            $viewad = $this->auth->getUserExtend('viewad');
            $viewtime = $this->auth->getUserExtend('viewtime');
            // if ($viewtime != strtotime(date('Y-m-d'))) {
                // $this->auth->setUserExtend('viewad',0);
                // $this->auth->setUserExtend('viewtime',strtotime(date('Y-m-d')));
                // $mineral = new MineralModel();
                // $mineral->where('user_id',$this->auth->id)->update(['today'=>0]);
                // echo $mineral->getLastSql();
            // }
        });

    }

    /**
     * 检测Token是否过期
     *
     */
    public function check()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        if ($this->auth->isLogin()) {
            $user = $this->auth->getUser();
            Hook::listen("user_check", $user);
        }

        $member_login = config('site.member_login');

        if ($member_login=='close') {
            $this->error('会员登陆已经关闭',['code'=>10],10);
        }
        
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

    /**
     * 刷新Token
     *
     */
    public function refresh()
    {
        $token = $this->auth->getToken();
        $tokenInfo = \app\common\library\Token::get($token);
        $tokenInfo->expiretime = time() + 2592000;
        $tokenInfo->save();
        $this->success('', ['token' => $tokenInfo['token'], 'expires_in' => $tokenInfo['expires_in']]);
    }

}
